//Copyright (C) 2010 Ron Coleman. Contact: ronncoleman@gmail.com
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 3 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this library; if not, write to the Free Software
//Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

/*
 * EditOrderDialog2.java
 *
 * Created on Dec 20, 2009, 10:22:39 AM
 */

package org.workplicity.marist.grounds.ui;

import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.workplicity.entry.Comment;
import org.workplicity.entry.User;
import org.workplicity.entry.WorkRequest;
import org.workplicity.entry.WorkRequest.Status;
import org.workplicity.entry.WorkSlate;
import org.workplicity.entry.event.Daily;
import org.workplicity.entry.event.Monthly;
import org.workplicity.entry.event.Once;
import org.workplicity.entry.event.Recurring;
import org.workplicity.entry.event.Weekdays;
import org.workplicity.entry.event.Weekly;
import org.workplicity.entry.event.Yearly;
import org.workplicity.marist.grounds.GroundsRequest;
import org.workplicity.marist.grounds.ui.table.CommentsTableModel;
import org.workplicity.marist.grounds.util.GroundsDate;
import org.workplicity.marist.grounds.util.GroundsHelper;
import org.workplicity.marist.grounds.util.SeasonalPresets;
import org.workplicity.marist.grounds.worklet.GroundsWorklet;
import org.workplicity.task.NetTask;
import org.workplicity.util.Helper;
import org.workplicity.util.Logger;
import org.workplicity.util.Resources;
import org.workplicity.util.WorkDate;
import org.workplicity.worklet.WorkletContext;

/**
 *
 * @author Ron Coleman
 */
public class EditOrderDialog2 extends javax.swing.JDialog {
    private final String method;

    private GroundsRequest request = null;
    private Recurring recurring = null;

    private WorkSlate targetWorkSlate = null;
    private WorkSlate sourceWorkSlate;
    private Status lastStatus;
    private final Status filterStatus;

    private WorkletContext context = GroundsWorklet.getInstance().getContext();
    private String initialCompleteDateText;
    private String[] springSelections = new String[0];
    private String[] winterSelections = new String[0];


    /** Creates new form EditOrderDialog2 */
    public EditOrderDialog2(java.awt.Frame parent, String method,GroundsRequest request, Status filterStatus) {
        super(parent, true);

        this.method = method;

        this.filterStatus = filterStatus;

        initComponents();

        this.setIconImage(Resources.logoSmall.getImage());

        this.setTitle("Grounds - " + method + " work request");

        this.setLocationRelativeTo(parent);

        this.request = request;

        initWithRequest();
    }

    private void initWithRequest() {
        this.lastStatus = request.getStatus();

        initFutures();
        
        initPrimary();

        initRequiredWork();

        initMaterials();

        initComments();
    }

    private void initPrimary() {
        this.statusComboBox.addItem(WorkRequest.Status.OPEN);
        this.statusComboBox.addItem(WorkRequest.Status.DISPATCHED);
        this.statusComboBox.addItem(WorkRequest.Status.STARTED);
        this.statusComboBox.addItem(WorkRequest.Status.HOLD);
        this.statusComboBox.addItem(WorkRequest.Status.FINISHED);

        if(Helper.isSuperUser(context))
            this.statusComboBox.addItem(WorkRequest.Status.CLOSED);

        // Initialize the date fields
        this.createDateTextField.setText(new GroundsDate(request.getCreateDate()).toString());
        this.requestDateTextField.setText(new GroundsDate(request.getRequestDate()).toString());

        // Initialize the fields with users
        ArrayList<User> users =
                GroundsWorklet.getInstance().getUsersCache().getCache();

        User defaultRequestUser = null;
        User defaultApprovingUser = null;
        User defaultSigningUser = null;

        for(User user : users) {
            this.signedByComboBox.addItem(user);
            this.approvedByComboBox.addItem(user);
            this.requestedByComboBox.addItem(user);

            if(user.getLogname().equals(request.getRequestedBy()))
                defaultRequestUser = user;

            if(user.getLogname().equals(request.getApprovedBy()))
                defaultApprovingUser = user;

            if(user.getLogname().equals(request.getSignedBy()))
                defaultSigningUser = user;
        }

        if(defaultRequestUser != null) {
            this.requestedByComboBox.setSelectedItem(defaultRequestUser);
            this.requestedByTextField.setEnabled(false);
        }
        else {
            if(request.getRequestedBy().length() != 0)
                this.requestedByTextField.setText(request.getRequestedBy());

            this.requestedByComboBox.setSelectedIndex(0);
            this.requestedByTextField.setEnabled(true);
        }

        if(defaultApprovingUser != null) {
            this.approvedByComboBox.setSelectedItem(defaultApprovingUser);
            this.approvedByTextField.setEnabled(false);
        }
        else {
            if(request.getApprovedBy().length() != 0)
                 this.approvedByTextField.setText(request.getApprovedBy());

            this.approvedByComboBox.setSelectedIndex(0);
            this.approvedByTextField.setEnabled(true);
        }

        if(defaultSigningUser != null) {
            this.signedByComboBox.setSelectedItem(defaultSigningUser);
            this.signedByCheckBox.setSelected(true);
            this.signedByComboBox.setEnabled(true);
            this.signedByTextField.setEnabled(false);
        }
        else {
            if (request.getSignedBy().length() != 0) {
                this.signedByComboBox.setSelectedIndex(0);
                this.signedByCheckBox.setSelected(true);
                this.signedByComboBox.setEnabled(true);
                this.signedByTextField.setEnabled(true);
                this.signedByTextField.setText(request.getSignedBy());
            } else {
                this.signedByComboBox.setSelectedIndex(0);
                this.signedByCheckBox.setSelected(false);
                this.signedByComboBox.setEnabled(false);
                this.signedByTextField.setEnabled(false);
            }
        }


        // Initialize the remainint fields
        if(request.getId() != -1)
            this.ridTextField.setText(request.getId()+"");

         // This is a new request...so we don't know the request id
        else {
            this.ridTextField.setText("N/A");
            this.statusComboBox.setEnabled(false);
//            this.requestDateTextField.setEnabled(false);
        }

        this.statusComboBox.setSelectedItem(request.getStatus());
        this.locationTextField.setText(request.getLocation());
        this.damageCauseTextField.setText(request.getDamageCause());
        this.signedByCheckBox.setSelected(request.isSigned());

        // If request CLOSED, prevent it from being saved
        if(request.getStatus() == WorkRequest.Status.CLOSED)
            this.saveButton.setEnabled(false);

        if(request.getId() != -1)
            this.requestDateTextField.setEnabled(false);
    }

    private void initRequiredWork() {
        // Get the work slates only for the current user and put them
        // on the combo box
        ArrayList<WorkSlate> workslates = null;

        // Put all work slates on the combo box, all if power user
        // or just mine otherwise
        if(Helper.isSuperUser(context)) {
            workslates = GroundsWorklet.getInstance().getWorkSlatesCache().getCache();
        }
        else {
            User me = (User) context.read(Resources.TAG_USER);

            workslates = GroundsHelper.getWorkSlates(me.getWorkSlateList());
        }

        for (WorkSlate workslate : workslates) {
            this.workslatesComboBox.addItem(workslate);
        }


        // If the order is already assigned to a work workSlate
        // set the work workSlate combo box to this work workSlate
        // and disable the combo box since the combo box
        // can't be changed (here) if it is set.

        if(this.targetWorkSlate != null) {
            this.workslatesComboBox.setSelectedItem(targetWorkSlate);

            // Can't change work workSlate here if it is already set (sorry)
//            this.workslatesComboBox.setEnabled(false);

            GroundsDate date = new GroundsDate(request.getAssignedDate());
            this.assignedDateTextField.setText(date.toString());
        }
        else {
            this.workslatesComboBox.setSelectedIndex(0);
            this.assignedDateTextField.setText("N/A");
        }

        // Set the rest of the fields
        this.workRequiredTextArea.setText(request.getDescr());
        this.chargeToTextField.setText(request.getChargeTo());

        if(request.getPriority() == GroundsRequest.Priority.URGENT)
            this.urgentButton.setSelected(true);
        else if(request.getPriority() == GroundsRequest.Priority.ROUTINE)
            this.routineButton.setSelected(true);

        this.reasonTextArea.setText(request.getReason());

        if(request.getStatus() == WorkRequest.Status.CLOSED)
            this.saveButton.setEnabled(false);

        // Set up the preset required work
        if(request.getId() != -1) {
            String[] lines = request.getDescr().split("\n");

            this.springSelections = GroundsHelper.capturePresets(lines, SeasonalPresets.SUFFIX_SPRING);

            this.winterSelections = GroundsHelper.capturePresets(lines, SeasonalPresets.SUFFIX_WINTER);
        }

        this.reconstituteRequiredWork();
    }

    private void initMaterials() {
        this.materialsTextArea.setText(request.getMaterials());

         if(request.getCompleteDate() != null) {
            GroundsDate date = new GroundsDate(request.getCompleteDate());

            this.completeDateTextField.setText(date.toString());
        }

        // Set initial complete date text to detect changes on save
        initialCompleteDateText = this.completeDateTextField.getText();

        this.estHrsTextField.setText(request.getEstHours()+"");
        this.actHrsTextField.setText(request.getActHours()+"");
    }

    private void initComments() {
        List<Comment> comments = request.getComments();
        Logger.log("initializing comments sz = "+comments.size());

        CommentsTableModel model = (CommentsTableModel)this.commentsTable.getModel();
        
        model.setComments(comments);
    }

    private void initFutures() {
        // By default the user won't be able to affect future events
        this.recurringCheckBox.setEnabled(false);
        this.suspendCheckBox.setEnabled(false);

        // If request is pointing to an event, initialize
        // the panel using the event, otherwise initialize the
        // recurring with default info
        Integer futureId = request.getFutureId();

        Integer requestId = request.getId();

        // If this is an existing request with no future component, set
        // the work slate
        if(requestId != -1 && !GroundsHelper.isRecurring(filterStatus)) {
            sourceWorkSlate = targetWorkSlate = GroundsHelper.getWorkSlate(request);

            return;
        }

        // Only super users can create or manipulate recurring requests
        if(!Helper.isSuperUser(context))
            return;

        // If this is an old request with a future component, we determine its
        // workslate using the request itself
        GroundsDate starts = null;
        GroundsDate ends = null;

        if(requestId != -1 && futureId != -1) {
            // Get the recurring event (whether true recurring or once event)
            recurring = (Recurring) Helper.fetch(NetTask.REPOS_FUTURES, futureId, context);

            // If the list is empty, it means the corresponding event has been
            // deleted which is okay; that just means this request no longer
            // has a reference event. We'll remove the reference here but the
            // old reference still persists in the repository -- a task
            // for GAUNTLET to clean up.
            if(recurring == null) {
                Logger.log("WARNING: intializing request id = "+request.getId()+" with recurring id = "+ futureId+ " failed");

                request.setFutureId(-1);

                sourceWorkSlate = targetWorkSlate = GroundsHelper.getWorkSlate(request);
                
                return;
            }

            this.recurringCheckBox.setEnabled(false);

            this.suspendCheckBox.setEnabled(false);

            // Otherwise use the event to get the work slate
            Integer wsid = recurring.getWorkSlateId();
                
            sourceWorkSlate = targetWorkSlate = GroundsHelper.getWorkSlate(wsid);

            // If this is a one-time request, the recurring panel
            // is not (and cannot be!) affected
            if(recurring instanceof Once)
                return;

            starts = new GroundsDate(recurring.getStarts());

            ends = new GroundsDate(recurring.getEnds());

            // Note: this little trick may not work to retrieve
            // the frequency depending if the combo box is checking
            // references or context at the reference
            String selection = recurring.getClass().getSimpleName();

            this.freqComboBox.setSelectedItem(selection);

            // Can't change frequency once it has been set
            this.freqComboBox.setEnabled(false);
            this.dayComboBox.setEnabled(false);

            // But...can enabled an old recurring
            this.suspendCheckBox.setEnabled(true);

            // This is a recurring request but it can ONLY be recurring
            this.recurringCheckBox.setSelected(true);
            this.recurringCheckBox.setEnabled(false);

            boolean suspend = !recurring.isEnabled();
            this.suspendCheckBox.setSelected(suspend);
        }
        else { // requestId == -1 (it's a new request && future == -1)
            // Start the default tomorrow
            Calendar cal1 = Calendar.getInstance();

            cal1.add(Calendar.DATE, 1);
            
            starts = new GroundsDate(cal1.getTimeInMillis());

            // End default one year from tomorrow
            Calendar cal2 = Calendar.getInstance();

            cal2.add(Calendar.DATE, 365);

            ends = new GroundsDate(cal2.getTimeInMillis());

            // This MAY become a recurring request
            this.recurringCheckBox.setSelected(false);
            this.recurringCheckBox.setEnabled(true);
        }

        this.startsTextField.setText(starts.toString());
        this.endsTextField.setText(ends.toString());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        createDateTextField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        ridTextField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        statusComboBox = new javax.swing.JComboBox();
        basicCalendarButton = new javax.swing.JButton();
        requestDateTextField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        requestedByComboBox = new javax.swing.JComboBox();
        requestedByTextField = new javax.swing.JTextField();
        approvedByTextField = new javax.swing.JTextField();
        approvedByComboBox = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        damageCauseTextField = new javax.swing.JTextField();
        jComboBox3 = new javax.swing.JComboBox();
        locationTextField = new javax.swing.JTextField();
        signedByCheckBox = new javax.swing.JCheckBox();
        signedByComboBox = new javax.swing.JComboBox();
        signedByTextField = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        workRequiredTextArea = new javax.swing.JTextArea();
        winterPresetButton = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        springPresetButton = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        workslatesComboBox = new javax.swing.JComboBox();
        assignedDateTextField = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        chargeToTextField = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        reasonTextArea = new javax.swing.JTextArea();
        urgentButton = new javax.swing.JRadioButton();
        routineButton = new javax.swing.JRadioButton();
        jPanel3 = new javax.swing.JPanel();
        actHrsTextField = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        completeDateTextField = new javax.swing.JTextField();
        estHrsTextField = new javax.swing.JTextField();
        materialsCalendarButton = new javax.swing.JButton();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        materialsTextArea = new javax.swing.JTextArea();
        jLabel22 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        commentsTable = new javax.swing.JTable();
        commetAddButton = new javax.swing.JButton();
        editCommentButton = new javax.swing.JButton();
        removeCommentButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        recurringCheckBox = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();
        freqComboBox = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        startsTextField = new javax.swing.JTextField();
        endsTextField = new javax.swing.JTextField();
        startsCalendarButton = new javax.swing.JButton();
        endsCalendarButton = new javax.swing.JButton();
        holidaysCheckBox = new javax.swing.JCheckBox();
        suspendCheckBox = new javax.swing.JCheckBox();
        holidaysComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        dayComboBox = new javax.swing.JComboBox();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTabbedPane1.setToolTipText("Enter basic information about the request.");

        jPanel1.setToolTipText("Enter basic information about the request.");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel5.setText("Requested:");

        createDateTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        createDateTextField.setText("mm / dd / yyyy");
        createDateTextField.setEnabled(false);

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel6.setText("Status:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel7.setText("Request id:");

        ridTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        ridTextField.setText("N/A");
        ridTextField.setEnabled(false);

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel8.setText("Created:");

        statusComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        statusComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                statusComboBoxItemStateChanged(evt);
            }
        });

        basicCalendarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cal.png"))); // NOI18N
        basicCalendarButton.setToolTipText("Click to open calendar.");
        basicCalendarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                basicCalendarButtonActionPerformed(evt);
            }
        });

        requestDateTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        requestDateTextField.setText("mm / dd / yyyy");

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel9.setText("Requester:");

        requestedByComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        requestedByComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<other>" }));
        requestedByComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                requestedByComboBoxItemStateChanged(evt);
            }
        });

        requestedByTextField.setFont(new java.awt.Font("Tahoma", 0, 12));

        approvedByTextField.setFont(new java.awt.Font("Tahoma", 0, 12));

        approvedByComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        approvedByComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<other>" }));
        approvedByComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                approvedByComboBoxItemStateChanged(evt);
            }
        });

        jLabel10.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel10.setText("Approver:");

        jLabel11.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel11.setText("Location:");

        jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel12.setText("Cause of damage:");

        damageCauseTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        damageCauseTextField.setText("N/A");

        jComboBox3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<other>" }));
        jComboBox3.setEnabled(false);

        locationTextField.setFont(new java.awt.Font("Tahoma", 0, 12));

        signedByCheckBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        signedByCheckBox.setText("Signed by:");
        signedByCheckBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                signedByCheckBoxItemStateChanged(evt);
            }
        });

        signedByComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        signedByComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<other>" }));
        signedByComboBox.setEnabled(false);
        signedByComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                signedByComboBoxItemStateChanged(evt);
            }
        });
        signedByComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                signedByComboBoxActionPerformed(evt);
            }
        });

        signedByTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        signedByTextField.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusComboBox, 0, 98, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ridTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
                .addGap(43, 43, 43))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(signedByCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(signedByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(signedByTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(damageCauseTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox3, 0, 101, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(locationTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(jLabel10)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(approvedByComboBox, 0, 101, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(approvedByTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(requestedByComboBox, 0, 101, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(requestedByTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 197, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(createDateTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel5)
                        .addGap(2, 2, 2)
                        .addComponent(requestDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(basicCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(ridTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(createDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(requestDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5))
                    .addComponent(basicCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel9)
                        .addComponent(requestedByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(requestedByTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel10)
                        .addComponent(approvedByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(approvedByTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(jComboBox3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(locationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(damageCauseTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(signedByCheckBox)
                    .addComponent(signedByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(signedByTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(177, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("", new javax.swing.ImageIcon(getClass().getResource("/work387.gif")), jPanel1); // NOI18N

        jPanel2.setToolTipText("Enter required work.");

        jScrollPane1.setFont(new java.awt.Font("Tahoma", 0, 14));

        workRequiredTextArea.setColumns(20);
        workRequiredTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
        workRequiredTextArea.setRows(5);
        jScrollPane1.setViewportView(workRequiredTextArea);

        winterPresetButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        winterPresetButton.setText("Winter Presets");
        winterPresetButton.setToolTipText("Click to select work presets.");
        winterPresetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                winterPresetButtonActionPerformed(evt);
            }
        });

        jLabel13.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel13.setText("Work required:");

        springPresetButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        springPresetButton.setText("Spring Presets");
        springPresetButton.setToolTipText("Click to select work presets.");
        springPresetButton.setActionCommand("Spring-Summer");
        springPresetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                springPresetButtonActionPerformed(evt);
            }
        });

        jLabel14.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel14.setText("Assigned date:");

        workslatesComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        workslatesComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<none>" }));
        workslatesComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                workslatesComboBoxItemStateChanged(evt);
            }
        });

        assignedDateTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        assignedDateTextField.setText("N/A");
        assignedDateTextField.setEnabled(false);

        jLabel15.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel15.setText("Work slate:");

        chargeToTextField.setFont(new java.awt.Font("Tahoma", 0, 12));

        jLabel16.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel16.setText("Priority:");

        jLabel17.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel17.setText("Charge to:");

        jLabel18.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel18.setText("Reason:");

        reasonTextArea.setColumns(20);
        reasonTextArea.setFont(new java.awt.Font("Monospaced", 0, 12));
        reasonTextArea.setRows(5);
        jScrollPane2.setViewportView(reasonTextArea);

        urgentButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        urgentButton.setText("Urgent");

        routineButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        routineButton.setSelected(true);
        routineButton.setText("Routine");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                            .addComponent(jLabel13)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                    .addGap(19, 19, 19)
                                    .addComponent(jLabel15)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(workslatesComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                    .addComponent(jLabel14)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(assignedDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(springPresetButton, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(winterPresetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(131, 131, 131))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel17)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(chargeToTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE)
                        .addGap(34, 34, 34))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel18)
                        .addContainerGap(347, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel16)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(routineButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(urgentButton)
                        .addContainerGap(211, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(workslatesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel14)
                    .addComponent(assignedDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel13)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(springPresetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(winterPresetButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(chargeToTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel16)
                    .addComponent(routineButton)
                    .addComponent(urgentButton))
                .addGap(3, 3, 3)
                .addComponent(jLabel18)
                .addGap(4, 4, 4)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11))
        );

        jTabbedPane1.addTab("", new javax.swing.ImageIcon(getClass().getResource("/work766.gif")), jPanel2); // NOI18N

        jPanel3.setToolTipText("Enter materials for or used by the request.");

        actHrsTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        actHrsTextField.setText("0.0");

        jLabel19.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel19.setText("Completion date:");

        completeDateTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        completeDateTextField.setText("mm / dd / yyyy");

        estHrsTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        estHrsTextField.setText("0.0");

        materialsCalendarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cal.png"))); // NOI18N
        materialsCalendarButton.setToolTipText("Click to open calendar.");
        materialsCalendarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                materialsCalendarButtonActionPerformed(evt);
            }
        });

        jLabel20.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel20.setText("Est. hrs:");

        jLabel21.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel21.setText("Act. hrs:");

        materialsTextArea.setColumns(20);
        materialsTextArea.setFont(new java.awt.Font("Tahoma", 0, 12));
        materialsTextArea.setRows(5);
        jScrollPane3.setViewportView(materialsTextArea);

        jLabel22.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel22.setText("Materials:");

        jButton5.setFont(new java.awt.Font("Tahoma", 0, 12));
        jButton5.setText("Inventory");
        jButton5.setEnabled(false);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel21)
                            .addComponent(jLabel20)
                            .addComponent(jLabel19))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(actHrsTextField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(estHrsTextField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(completeDateTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(materialsCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel22)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton5))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel22)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton5)
                .addGap(11, 11, 11)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel19)
                        .addComponent(completeDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(materialsCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(estHrsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel20))
                .addGap(8, 8, 8)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(actHrsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel21))
                .addGap(132, 132, 132))
        );

        jTabbedPane1.addTab("", new javax.swing.ImageIcon(getClass().getResource("/cart.png")), jPanel3); // NOI18N

        jPanel4.setToolTipText("Enter comments about or for the request.");

        commentsTable.setFont(new java.awt.Font("Tahoma", 0, 12));
        commentsTable.setModel(new CommentsTableModel( ));
        jScrollPane4.setViewportView(commentsTable);

        commetAddButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/add2.png"))); // NOI18N
        commetAddButton.setToolTipText("Click this button to add the comment.");
        commetAddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commetAddButtonActionPerformed(evt);
            }
        });

        editCommentButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/drill2.png"))); // NOI18N
        editCommentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editCommentButtonActionPerformed(evt);
            }
        });

        removeCommentButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/remove4.png"))); // NOI18N
        removeCommentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeCommentButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(commetAddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeCommentButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(editCommentButton, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(editCommentButton, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(removeCommentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(commetAddButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE))
                .addGap(179, 179, 179))
        );

        jTabbedPane1.addTab("", new javax.swing.ImageIcon(getClass().getResource("/pencil.png")), jPanel4); // NOI18N

        jPanel5.setToolTipText("Enter information about a forward or recurring request.");

        recurringCheckBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        recurringCheckBox.setText("Recurring request");
        recurringCheckBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                recurringCheckBoxItemStateChanged(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Frequency:");

        freqComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        freqComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Weekdays", "Daily", "Weekly", "Monthly", "Yearly", "Once" }));
        freqComboBox.setEnabled(false);
        freqComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                freqComboBoxItemStateChanged(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Starts:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("Ends:");

        startsTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        startsTextField.setText("mm / dd / yyyy");
        startsTextField.setEnabled(false);

        endsTextField.setFont(new java.awt.Font("Tahoma", 0, 12));
        endsTextField.setText("mm / dd / yyyy");
        endsTextField.setEnabled(false);

        startsCalendarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cal.png"))); // NOI18N
        startsCalendarButton.setToolTipText("Click to open calendar.");
        startsCalendarButton.setEnabled(false);
        startsCalendarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startsCalendarButtonActionPerformed(evt);
            }
        });

        endsCalendarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/cal.png"))); // NOI18N
        endsCalendarButton.setToolTipText("Click to open calendar.");
        endsCalendarButton.setEnabled(false);
        endsCalendarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                endsCalendarButtonActionPerformed(evt);
            }
        });

        holidaysCheckBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        holidaysCheckBox.setText("Use holidays");
        holidaysCheckBox.setEnabled(false);

        suspendCheckBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        suspendCheckBox.setText("Temporarily suspend");
        suspendCheckBox.setEnabled(false);

        holidaysComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        holidaysComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "N/A" }));
        holidaysComboBox.setEnabled(false);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel4.setText("Day:");

        dayComboBox.setFont(new java.awt.Font("Tahoma", 0, 12));
        dayComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "N/A" }));
        dayComboBox.setEnabled(false);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(recurringCheckBox)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel5Layout.createSequentialGroup()
                                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addGap(10, 10, 10)
                                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(endsTextField)
                                    .addComponent(startsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(endsCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(startsCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel5Layout.createSequentialGroup()
                                    .addComponent(holidaysCheckBox)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(holidaysComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(jPanel5Layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(freqComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(suspendCheckBox)))
                        .addGap(18, 18, 18)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dayComboBox, 0, 133, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(recurringCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(freqComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(dayComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(startsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(endsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(startsCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(endsCalendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(holidaysCheckBox)
                    .addComponent(holidaysComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(suspendCheckBox)
                .addContainerGap(217, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("", new javax.swing.ImageIcon(getClass().getResource("/roadahead.png")), jPanel5); // NOI18N

        cancelButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setFont(new java.awt.Font("Tahoma", 0, 12));
        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(253, Short.MAX_VALUE)
                .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelButton)
                .addContainerGap())
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void basicCalendarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicCalendarButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                WorkDate date = Helper.toDate(requestDateTextField.getText());

                CalendarDialog3 calendar = new CalendarDialog3(dialog,date);

                calendar.setVisible(true);
                if(calendar.getCalendar() == null)
                    return;

                int year = calendar.getCalendar().get(Calendar.YEAR);
                int mon = calendar.getCalendar().get(Calendar.MONTH) + 1;
                int day = calendar.getCalendar().get(Calendar.DAY_OF_MONTH);

                String mons = mon < 10 ? "0"+mon : mon+"";
                String days = day < 10 ? "0"+day : day+"";

                dialog.requestDateTextField.setText(mons + " / " + days + " / "+year);

            }
        });
    }//GEN-LAST:event_basicCalendarButtonActionPerformed

    private void requestedByComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_requestedByComboBoxItemStateChanged
        if(this.requestedByComboBox.getSelectedIndex() == 0)
            this.requestedByTextField.setEnabled(true);
        else {
            this.requestedByTextField.setEnabled(false);
            this.requestedByTextField.setText("");
        }
}//GEN-LAST:event_requestedByComboBoxItemStateChanged

    private void approvedByComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_approvedByComboBoxItemStateChanged
        if(this.approvedByComboBox.getSelectedIndex() == 0)
            this.approvedByTextField.setEnabled(true);
        else {
            this.approvedByTextField.setEnabled(false);
            this.approvedByTextField.setText("");
        }
}//GEN-LAST:event_approvedByComboBoxItemStateChanged

    private void signedByCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_signedByCheckBoxItemStateChanged
        boolean selected = this.signedByCheckBox.isSelected();
        this.signedByTextField.setEnabled(selected);
        this.signedByComboBox.setEnabled(selected);

        if(!selected) {
            this.signedByTextField.setText("");
            this.signedByComboBox.setSelectedIndex(0);
        }

}//GEN-LAST:event_signedByCheckBoxItemStateChanged

    private void workslatesComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_workslatesComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        // If the work workSlate selection says "<none>", clear the assignment date
        // and target workslate and set the status combo to OPEN.
        // On save this will cause the request to be removed from
        // its work workSlate, if necessary. The same applies if on save
        // the status combo says CLOSED.
        if(this.workslatesComboBox.getSelectedIndex() == 0) {
            this.assignedDateTextField.setText("N/A");

            this.targetWorkSlate = null;

            WorkRequest.Status status = (WorkRequest.Status) this.statusComboBox.getSelectedItem();

            if(status == Status.CLOSED)
                this.statusComboBox.setSelectedItem(Status.CLOSED);
            else
                this.statusComboBox.setSelectedItem(Status.OPEN);

            this.statusComboBox.setEnabled(false);

            return;
        }

        // Update the date request is being assigned to a new work workSlate
        GroundsDate date = new GroundsDate(System.currentTimeMillis());
        this.assignedDateTextField.setText(date.toString());

        // Set the target work workSlate to the one in the combo box
        targetWorkSlate = (WorkSlate) workslatesComboBox.getSelectedItem();

        // If this is a new request or it's OPEN/CLOSED, set the default status to dispatched
        // otherwise leave it to whatever the user set
        WorkRequest.Status status = (WorkRequest.Status) statusComboBox.getSelectedItem();

        if(request.getId() == -1 || status == WorkRequest.Status.OPEN || status == WorkRequest.Status.CLOSED)
            this.statusComboBox.setSelectedItem(Status.DISPATCHED);

        // Set the status combo to enabled since there is now a work workSlate
        this.statusComboBox.setEnabled(true);
}//GEN-LAST:event_workslatesComboBoxItemStateChanged

    private void materialsCalendarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_materialsCalendarButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                String d = getCalendarDate(completeDateTextField.getText());

                dialog.completeDateTextField.setText(d);
            }
        });
}//GEN-LAST:event_materialsCalendarButtonActionPerformed

    private void startsCalendarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startsCalendarButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                String d = getCalendarDate(startsTextField.getText());

                dialog.startsTextField.setText(d);
            }
        });
    }//GEN-LAST:event_startsCalendarButtonActionPerformed

    private void endsCalendarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endsCalendarButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                String d = getCalendarDate(endsTextField.getText());

                dialog.endsTextField.setText(d);
            }
        });
    }//GEN-LAST:event_endsCalendarButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!valid())
                        return;

                    if (!scrapeRequest())
                        return;

                    long now = System.currentTimeMillis();

                    if(dialog.recurringCheckBox.isSelected())
                        insertRecurring();
                    
                    else if(recurring instanceof Once || request.getRequestDate().getTime() > now)
                        insertOnce();
                    
                    else
                        insertRegular();

                    dialog.dispose();

                } catch (Exception e) {
                    Logger.log(e.toString());
                }
            }
        });

        return;
    }//GEN-LAST:event_saveButtonActionPerformed

    private void recurringCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_recurringCheckBoxItemStateChanged
        boolean enabled = false;
        
        if(this.recurringCheckBox.isSelected())
            enabled = true;

        this.startsTextField.setEnabled(enabled);
        this.endsTextField.setEnabled(enabled);
        this.startsCalendarButton.setEnabled(enabled);
        this.endsCalendarButton.setEnabled(enabled);
        
        // Can't enabled a new request or change the frequency of an old one
        if(request.getId() == -1) {
            this.suspendCheckBox.setEnabled(false);
            this.freqComboBox.setEnabled(true);
            this.dayComboBox.setEnabled(false);
        }
        else {
            this.suspendCheckBox.setEnabled(true);
            this.freqComboBox.setEnabled(false);
            this.dayComboBox.setEnabled(false);
        }
        

    }//GEN-LAST:event_recurringCheckBoxItemStateChanged

    private void freqComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_freqComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        String selection = (String) this.freqComboBox.getSelectedItem();

        dayComboBox.removeAllItems();

        if(selection.equals("Weekly")) {
            this.dayComboBox.setEnabled(true);
            String[] weekly = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
            for(int i=0; i < weekly.length; i++)
                dayComboBox.addItem(weekly[i]);

            if(recurring instanceof Weekly) {
                String day = recurring.getPattern().split(" +")[4];

                // Day in cron4j start at index = 1
                dayComboBox.setSelectedIndex(Integer.parseInt(day)-1);
            }
        }
        else if(selection.equals("Monthly")) {
            this.dayComboBox.setEnabled(true);

            for(int i=1; i <= 31; i++) {
                dayComboBox.addItem(i+"");
            }

            if(recurring instanceof Monthly) {
                String day = recurring.getPattern().split(" +")[2];
                dayComboBox.setSelectedItem(day);
            }
        }
        else {
            dayComboBox.setEnabled(false);

            dayComboBox.addItem("N/A");
        }
    }//GEN-LAST:event_freqComboBoxItemStateChanged

    private void springPresetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_springPresetButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    showPresetsDialog(SeasonalPresets.NAME_SPRING,dialog.springSelections,SeasonalPresets.SUFFIX_SPRING);
                } catch (Exception e) {
                    Logger.log(e.toString());
                }
            }
        });
    }//GEN-LAST:event_springPresetButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void winterPresetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_winterPresetButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    showPresetsDialog(SeasonalPresets.NAME_WINTER,dialog.winterSelections,SeasonalPresets.SUFFIX_WINTER);
                } catch (Exception e) {
                    Logger.log(e.toString());
                }
            }
        });
    }//GEN-LAST:event_winterPresetButtonActionPerformed

    private void statusComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_statusComboBoxItemStateChanged
        // Combo boxes send two events: one for the deselected item
        // and one for the selected one -- we only want the selected one
        if(evt.getStateChange() == ItemEvent.DESELECTED)
            return;

        // If the status says OPEN or CLOSED, clear the work workSlate to "<none>"
        WorkRequest.Status status = (WorkRequest.Status) this.statusComboBox.getSelectedItem();

        if(status == WorkRequest.Status.OPEN || status == WorkRequest.Status.CLOSED) {
            // NOTE: this "if" is needed to prevent an infinite event loop between
            // status and workslate combo boxes
            if(workslatesComboBox.getSelectedIndex() != 0)
                this.workslatesComboBox.setSelectedIndex(0);
        }
    }//GEN-LAST:event_statusComboBoxItemStateChanged

    private void commetAddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commetAddButtonActionPerformed
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    EditCommentDialog commentDialog =
                            new EditCommentDialog(dialog,Helper.whoAmI(context),request,dialog.commentsTable,true);

                    commentDialog.setVisible(true);
                    
                } catch (Exception e) {
                    Logger.log(e.toString());
                }
            }
        });
    }//GEN-LAST:event_commetAddButtonActionPerformed

    private void editCommentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editCommentButtonActionPerformed
        if(this.commentsTable.getSelectedRow() == -1)
            return;
        
        final EditOrderDialog2 dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    EditCommentDialog commentDialog =
                            new EditCommentDialog(dialog,Helper.whoAmI(context),request,dialog.commentsTable,false);

                    commentDialog.setVisible(true);

                } catch (Exception e) {
                    Logger.log(e.toString());
                }
            }
        });
    }//GEN-LAST:event_editCommentButtonActionPerformed

    private void removeCommentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeCommentButtonActionPerformed
        int row = this.commentsTable.getSelectedRow();

        if(row == -1)
            return;

        CommentsTableModel model = (CommentsTableModel) commentsTable.getModel();

        List<Comment> comments = model.getComments();

        Comment comment = comments.get(row);

        if (request.getId() != -1 && comment.getDate().getTime() < request.getUpdateDate().getTime()) {
            JOptionPane.showMessageDialog(this, "Can't remove old comments.",
                    "Grounds", JOptionPane.ERROR_MESSAGE);

            return;
        }

        comments.remove(row);

        model.fireTableDataChanged();
    }//GEN-LAST:event_removeCommentButtonActionPerformed

    private void signedByComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_signedByComboBoxActionPerformed

    }//GEN-LAST:event_signedByComboBoxActionPerformed

    private void signedByComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_signedByComboBoxItemStateChanged
        boolean enabled = this.signedByComboBox.getSelectedIndex() == 0 && this.signedByCheckBox.isSelected();
        this.signedByTextField.setEnabled(enabled);

        if(this.signedByComboBox.getSelectedIndex() != 0)
            this.signedByTextField.setText("");
    }//GEN-LAST:event_signedByComboBoxItemStateChanged

    private void showPresetsDialog(String presetsFile,String[] selections, String suffix) throws Exception {
        WorkPresetsDialog presetsDialog =
                new WorkPresetsDialog(this, presetsFile, selections, suffix);

        presetsDialog.setVisible(true);

        if(presetsDialog.isCanceled())
            return;
        
        if(suffix.equals(SeasonalPresets.SUFFIX_SPRING))
            this.springSelections = presetsDialog.getSelections();
        else
            this.winterSelections = presetsDialog.getSelections();

        this.reformatRequiredWork();
    }

    private void reformatRequiredWork() {
        String[] lines = workRequiredTextArea.getText().split("\n");
        String[] nonPresets =
                GroundsHelper.filterPresets(lines, SeasonalPresets.SUFFIX_SPRING);

        nonPresets =
                GroundsHelper.filterPresets(nonPresets,  SeasonalPresets.SUFFIX_WINTER);

        workRequiredTextArea.removeAll();

        String text = "";

        for(int i=0; i < nonPresets.length; i++) {
            if(i != 0)
                text += "\n";

            text += nonPresets[i];
        }

//        int index = 1;

        if(text.length() != 0 && springSelections.length != 0)
            text += "\n";

        for(int i=0; i < springSelections.length; i++) {
            if(i != 0)
                text += "\n";
//            text += index + "> " + springSelections[i];
//
//            index++;

            text += "** " + springSelections[i];
        }

        if((text.length() != 0 || springSelections.length != 0) && winterSelections.length != 0)
            text += "\n";

        for(int i=0; i < winterSelections.length; i++) {
            if(i != 0)
                text += "\n";
//            text += index + "> " + winterSelections[i];
//
//            index++;

            text += "** " + winterSelections[i];
        }

        workRequiredTextArea.setText(text);
    }
    
    private void insertRegular() {
        if (method.startsWith("Create") || method.startsWith("Update")) {
            Logger.log("request insert started request id=" + request.getId());

            if (this.statusComboBox.getSelectedItem() == WorkRequest.Status.OPEN ||
                    this.statusComboBox.getSelectedItem() == WorkRequest.Status.CLOSED) {
                targetWorkSlate = null;
            }

            boolean successful = Helper.insert(request, NetTask.REPOS_CLEARINGHOUSE, context);
            Logger.log("inserted request id=" + request.getId() + " date=" + new Date(request.getRequestDate().getTime()));

            // Now that the request has been inserted, remove it from the source
            // and put it on the target work workSlate, if necessary.
            if (successful) {
                if (targetWorkSlate != sourceWorkSlate) {
                    successful = updateSourceWorkSlate();

                    if (successful) {
                        successful = updateTargetWorkSlate();
                    }
                }
            }

            if (successful) {
                JOptionPane.showMessageDialog(this, "Successfully saved request id=" + request.getId(),
                        "Grounds", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Request save failed, see diags for details.",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void insertRecurring() {
        // Since the server updates the event's update date each time
        // the server is restarted or the event rescheduled, we must
        // use the request's update date to properly reflect the
        // the "true" updates
        request.setUpdateDate(new WorkDate());

        // Add the template
        recurring.setTemplate(request);

        boolean successful = Helper.insert(recurring, NetTask.REPOS_FUTURES, context);

        if (successful) {
            String name = recurring.getClass().getSimpleName().toUpperCase();
            JOptionPane.showMessageDialog(this, "Successfully saved "+name+" request id = " + recurring.getId(),
                    "Grounds", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "Recurring request save failed.",
                    "Grounds", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void insertOnce() {
        // Since the server updates the event's update date each time
        // the server is restarted or the event rescheduled, we must
        // use the request's update date to properly reflect the
        // the "true" updates
        request.setUpdateDate(new WorkDate());

        // Get the event.
        Once once = null;
        if(recurring == null) {
            WorkDate starts = request.getRequestDate();

            once = new Once(starts);

            once.setEnabled(true);
        }
        else
            once = (Once) recurring;

        // Add the template
        once.setTemplate(request);

        // Set all the ancillary but important stuff
        once.setServiceId(context.getSvcId());

        once.setUpdateUserId(Helper.whoAmI(context).getId());

        // Update the work slate id
        if(this.workslatesComboBox.getSelectedIndex() != 0) {
            WorkSlate workSlate = (WorkSlate) workslatesComboBox.getSelectedItem();
            
            once.setWorkSlateId(workSlate.getId());
        }
        else
            once.setWorkSlateId(-1);

        // Set the service id
        once.setServiceId(request.getServiceId());

        // Insert the event
        boolean successful = Helper.insert(once, NetTask.REPOS_FUTURES, context);

        if (successful) {
            String name = once.getClass().getSimpleName().toUpperCase();
            JOptionPane.showMessageDialog(this, "Successfully saved "+name+" request id = " + once.getId(),
                    "Grounds", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "Request save failed.",
                    "Grounds", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String getCalendarDate(String text) {
        WorkDate date = Helper.toDate(text);
        CalendarDialog3 calendar = new CalendarDialog3(this, date);

        calendar.setVisible(true);
        if (calendar.getCalendar() == null) {
            return null;
        }

        int year = calendar.getCalendar().get(Calendar.YEAR);
        int mon = calendar.getCalendar().get(Calendar.MONTH) + 1;
        int day = calendar.getCalendar().get(Calendar.DAY_OF_MONTH);

        String mons = mon < 10 ? "0" + mon : mon + "";
        String days = day < 10 ? "0" + day : day + "";


        String s = mons + " / " + days + " / " + year;

        return s;
    }

    private boolean valid() {
        // Issue an error if the status requires a work workSlate
        // and there isn't one.
        WorkRequest.Status status = (WorkRequest.Status) this.statusComboBox.getSelectedItem();

        if (GroundsHelper.needsWorkSlate(status) && targetWorkSlate == null) {
            String msg = "The request status requires a work slate.";

            JOptionPane.showMessageDialog(this, msg,
                    "Grounds", JOptionPane.ERROR_MESSAGE);

            this.statusComboBox.setSelectedItem(this.lastStatus);

            return false;
        }

        // Issue warning about open work requests.

        if (targetWorkSlate == null && status == WorkRequest.Status.OPEN) {
            String msg = "Work request is not assigned to a work slate.";
            msg += "\nIt's status will be OPEN. Proceed?";

            int n = JOptionPane.showConfirmDialog(
                    this,
                    msg,
                    "Confirm",
                    JOptionPane.YES_NO_OPTION);

            if (n == 1) {
                return false;
            }
        }

        // Issue warning if request targetWorkSlate to work workSlate I'm NOT referencing
        if (targetWorkSlate != null) {
            if (!GroundsHelper.isMy(targetWorkSlate,context)) {
                String msg = "Work request being assigned to '" + targetWorkSlate.getName() + "',";
                msg += "\nwhich is NOT one of yours. Proceed?";

                int n = JOptionPane.showConfirmDialog(
                        this,
                        msg,
                        "Confirm",
                        JOptionPane.YES_NO_OPTION);

                if (n == 1) {
                    return false;
                }
            }
        }

        // Issue an error if trying to make an existing non-recurring request
        // recurring
        if(request.getId() != -1 && recurring == null && this.recurringCheckBox.isSelected()) {
            String msg = "Can't make non-recurring request recurring";

            JOptionPane.showMessageDialog(this, msg,
                    "Grounds", JOptionPane.ERROR_MESSAGE);

            return false;
        }

        // Issue an error if trying to make an existing recurring request
        // non-recurring
        if(request.getId() != -1 && recurring != null && !this.recurringCheckBox.isSelected()) {
            if(!(recurring instanceof Once)) {
                String msg = "Can't make recurring request non-recurring";

                JOptionPane.showMessageDialog(this, msg,
                        "Grounds", JOptionPane.ERROR_MESSAGE);

                return false;
            }
        }

        if(status == WorkRequest.Status.CLOSED) {
            String msg = "The request status is being CLOSED.";
            msg += "\nYou won't be able to edit it further. Proceed?";

            int n = JOptionPane.showConfirmDialog(
                    this,
                    msg,
                    "Confirm",
                    JOptionPane.YES_NO_OPTION);

            if (n == 1) {
                return false;
            }
        }
        return checkDates();
    }

    private boolean checkDates() {
        WorkDate date = Helper.toDate(this.requestDateTextField.getText());

        if (date == null) {
            JOptionPane.showMessageDialog(this, "Bad request date format.",
                    "Grounds", JOptionPane.ERROR_MESSAGE);

            return false;
        }

        long now = System.currentTimeMillis();

        if (date.getTime() > now) {
            String msg = "Request date is in the future. It will be";
            msg += "\nscheduled as PENDING for later. Proceed?";

            int answer =
                    JOptionPane.showConfirmDialog(this,
                    msg, "Confirm",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);

            if(answer != 0)
                return false;
        }
//        else if (date.getTime() > now && request.getStatus() != WorkRequest.Status.OPEN) {
//            JOptionPane.showMessageDialog(dialog, "Future requests must be OPEN.",
//                    "Grounds", JOptionPane.ERROR_MESSAGE);
//            return false;
//        }

        // Check the recurring dates, if necessary
        if (this.recurringCheckBox.isSelected()) {
            WorkDate starts = Helper.toDate(this.startsTextField.getText());
            if (date == null) {
                JOptionPane.showMessageDialog(this, "Bad recurring starts date format.",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            WorkDate ends = Helper.toDate(this.endsTextField.getText());
            if (date == null) {
                JOptionPane.showMessageDialog(this, "Bad recurring ends date format.",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            if (starts.getTime() > ends.getTime()) {
                JOptionPane.showMessageDialog(this, "Recurring ends date before start date.",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            if(ends.getTime() < now) {
                JOptionPane.showMessageDialog(this, "Recurring ends date is before now.",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            String selection = (String) freqComboBox.getSelectedItem();
            
            if(selection.equals("Once") && starts.getTime() < now) {
                JOptionPane.showMessageDialog(this, "Once start date is before now.",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
                return false;
            }

        }

        return true;
    }

    /**
     * Reverts the request to the open state in terms of its work workSlate.
     * @return True if successful
     */
    private boolean updateSourceWorkSlate() {
        if(sourceWorkSlate == null)
            return true;

        Logger.log("source work slate update started");

        Logger.log("removing request id="+request.getId()+" status="+request.getStatus()+" from work slate='"+sourceWorkSlate.getName()+"'");

        // Find the key id and remove it from the source
        Integer id = null;

        for (Integer keyId : sourceWorkSlate.getWorkRequestList()) {
            if (keyId.equals(request.getId())) {
                id = keyId;
                break;
            }
        }

        if(id == null)  {
            Logger.log("INTERNAL ERROR: request id='"+request.getId()+"' not found on src work slate='"+sourceWorkSlate.getName()+"'");
            return false;
        }

        sourceWorkSlate.getWorkRequestList().remove(id);

        boolean successful = Helper.insert(sourceWorkSlate,NetTask.REPOS_WORKSLATES, context);

        return successful;
    }
    private boolean updateTargetWorkSlate() {
        if(targetWorkSlate == null)
            return true;

        Logger.log("target work slate update started");

        // Add request to the workSlate only if
        // request is not already on target workSlate
        for(Integer keyId : targetWorkSlate.getWorkRequestList()) {
            if(keyId.equals(request.getId())) {
                Logger.log("request="+request.getId()+" already on work slate='"+targetWorkSlate.getName()+"'");
                return true;
            }
        }

        // Add work request to new work workSlate
        Logger.log("adding request="+request.getId()+" to work slate='"+targetWorkSlate.getName()+"'");

        targetWorkSlate.getWorkRequestList().add(request.getId());

        boolean successful = Helper.insert(targetWorkSlate, NetTask.REPOS_WORKSLATES,context);

        if(successful)
            Logger.log("successfully added request="+request.getId()+" to target work slate='"+targetWorkSlate.getName()+"'");

        return successful;
    }

    private boolean scrapeRequest() {
        if(!scrapeMaterials())
            return false;

        if(!scrapeRequiredWork())
            return false;

        if(!scrapeComments())
            return false;

        if(!scrapeFuture())
            return false;

        if(!scrapePrimary())
            return false;

        return true;
    }

    private boolean scrapePrimary() {
        request.setLocation(this.locationTextField.getText());

        Logger.log("request date text field = "+this.requestDateTextField.getText());

        WorkDate date = Helper.toDate(this.requestDateTextField.getText());
        request.setRequestDate(date);

        Logger.log("request date instance = "+new Date(request.getRequestDate().getTime()));

        User me = (User) GroundsWorklet.getInstance().getContext().read(Resources.TAG_USER);

        request.setStatus(me.getId(), (WorkRequest.Status) this.statusComboBox.getSelectedItem());

        request.setDamageCause(this.damageCauseTextField.getText());

        // if a NEW request...
        if (request.getId() == -1) {
            request.setCreateUserId(me.getId());
        }

        if (this.requestedByComboBox.getSelectedIndex() == 0) {
            request.setRequestedBy(this.requestedByTextField.getText());
        } else {
            User requestor = (User) this.requestedByComboBox.getSelectedItem();
            request.setRequestedBy(requestor.getLogname());
        }

        if (this.approvedByComboBox.getSelectedIndex() == 0) {
            request.setApprovedBy(this.approvedByTextField.getText());
        } else {
            User approver = (User) this.approvedByComboBox.getSelectedItem();
            request.setApprovedBy(approver.getLogname());
        }

        request.setSigned(this.signedByCheckBox.isSelected());

        if (this.signedByComboBox.getSelectedIndex() == 0) {
            request.setSignedBy(this.signedByTextField.getText());
        } else {
            User signer = (User) this.signedByComboBox.getSelectedItem();
            request.setSignedBy(signer.getLogname());
        }

        return true;
    }

    /**
     * Scrape the screen of the required work by extracting the
     * the non-presets, adding them to a new description, and then adding
     * the presets. The numbered items (ie, the presets) that are in the
     * text are component are removed by virtue of extracting the non-presets
     * from the text area.
     * @return True if successful
     */
    private boolean scrapeRequiredWork() {
        request.setReason(this.reasonTextArea.getText());
        request.setDescr(this.workRequiredTextArea.getText());

        if(this.urgentButton.isSelected())
            request.setPriority(GroundsRequest.Priority.URGENT);

        else if(this.routineButton.isSelected())
            request.setPriority(GroundsRequest.Priority.ROUTINE);

        request.setChargeTo(this.chargeToTextField.getText());

        if(this.workslatesComboBox.getSelectedIndex() != 0) {
            targetWorkSlate = (WorkSlate) this.workslatesComboBox.getSelectedItem();

            WorkDate date = Helper.toDate(this.assignedDateTextField.getText());

            request.setAssignedDate(date);
        }
        else {
            targetWorkSlate = null;
            request.setAssignedDate(null);
        }

        // Code the presets into the description to make
        // them easier to reconstitute them on reload.
        codeDescription();

        return true;
    }

    /**
     * Code the required work with tags
     */
    private void codeDescription() {
        String[] nonPresets = GroundsHelper.filterPresets(request.getDescr().split("\n"), SeasonalPresets.SUFFIX_SPRING);

        nonPresets = GroundsHelper.filterPresets(nonPresets,SeasonalPresets.SUFFIX_WINTER);

        String descr = "";
        for(int i=0; i < nonPresets.length; i++) {
            if(i != 0)
                descr += "\n";

            descr += nonPresets[i];
        }

        if(nonPresets.length != 0 && springSelections.length != 0)
            descr += "\n";

        for(int i=0; i < springSelections.length; i++) {
            if(i != 0)
                descr += "\n";

            descr += springSelections[i];
        }

        if((nonPresets.length != 0 || springSelections.length != 0) && winterSelections.length != 0)
            descr += "\n";

        for(int i=0; i < winterSelections.length; i++) {
            if(i != 0)
                descr += "\n";
            
            descr += winterSelections[i];
        }

        request.setDescr(descr);
    }

    private void reconstituteRequiredWork() {
        String[] lines = this.workRequiredTextArea.getText().split("\n");

        springSelections = GroundsHelper.capturePresets(lines, SeasonalPresets.SUFFIX_SPRING);
        winterSelections = GroundsHelper.capturePresets(lines, SeasonalPresets.SUFFIX_WINTER);

        this.reformatRequiredWork();
    }

    private boolean scrapeMaterials() {
        String curCompleteDateText = this.completeDateTextField.getText();

        if (!this.initialCompleteDateText.equals(curCompleteDateText)) {
            WorkDate date = Helper.toDate(curCompleteDateText);

            if (date == null) {
                JOptionPane.showMessageDialog(this, "Bad complete date: must be MM/DD/YYYY",
                        "Grounds", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            request.setCompleteDate(date);
        }

        try {
            request.setEstHours(Double.parseDouble(this.estHrsTextField.getText()));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Bad est. hrs.: must be a number",
                    "Grounds", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        try {
            request.setActHours(Double.parseDouble(this.actHrsTextField.getText()));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Bad act. hrs.: must be a number",
                    "Grounds", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        request.setMaterials(this.materialsTextArea.getText());

        return true;
    }

    private boolean scrapeComments() {
        return true;
    }

    private boolean scrapeFuture() {
        if(!this.recurringCheckBox.isSelected())
            return true;

        // If there is no recurring event, create one
        if(recurring == null) {
            String selection = (String) this.freqComboBox.getSelectedItem();

            recurring = getRecurring(selection);
        }

        // Set the template to the request
        recurring.setTemplate(request);

        // Set the ancillary stuff
        recurring.setServiceId(context.getSvcId());
        
        recurring.setUpdateUserId(Helper.whoAmI(context).getId());

        recurring.setStarts(Helper.toDate(this.startsTextField.getText()));
        recurring.setEnds(Helper.toDate(this.endsTextField.getText()));

        boolean enabled = !this.suspendCheckBox.isSelected();
        recurring.setEnabled(enabled);

        if(this.workslatesComboBox.getSelectedIndex() == 0)
            recurring.setWorkSlateId(-1);
        else {
            WorkSlate workSlate = (WorkSlate) workslatesComboBox.getSelectedItem();

            recurring.setWorkSlateId(workSlate.getId());
        }
        
        return true;
    }

    private Recurring getRecurring(String selection) {
        WorkDate starts = Helper.toDate(this.startsTextField.getText());
        WorkDate ends = Helper.toDate(this.endsTextField.getText());

        Recurring recurs = null;

        if(selection.equals("Weekdays")) {
            recurs = new Weekdays(starts,ends);
        }
        else if(selection.equals("Weekly")) {
            int day = this.dayComboBox.getSelectedIndex() + 1;

            recurs = new Weekly(day,starts,ends);
        }
        else if(selection.equals("Daily")) {
            recurs = new Daily(starts,ends);
        }
        else if(selection.equals("Monthly")) {
            int day = this.dayComboBox.getSelectedIndex() + 1;

            recurs = new Monthly(day,starts,ends);
        }
        else if(selection.equals("Yearly")) {
            Calendar cal = Calendar.getInstance();

            cal.setTime(starts);

            int day = cal.get(Calendar.DAY_OF_MONTH);

            // Calendar returns 0=jan, 1=feb, ... but cron4j wants 1=jan, 2=feb, ...
            int mon = cal.get(Calendar.MONTH) + 1;

            recurs = new Yearly(day,mon,starts,ends);

        }
        else if(selection.equals("Once")) {
            recurs = new Once(starts);
        }

        // Get the work workSlate and store it in the event
        // since there's no other place to keep this info
        if(targetWorkSlate != null)
            recurs.setWorkSlateId(targetWorkSlate.getId());
        
        return recurs;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                EditOrderDialog2 dialog = new EditOrderDialog2(new javax.swing.JFrame(), null,null,null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField actHrsTextField;
    private javax.swing.JComboBox approvedByComboBox;
    private javax.swing.JTextField approvedByTextField;
    private javax.swing.JTextField assignedDateTextField;
    private javax.swing.JButton basicCalendarButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField chargeToTextField;
    private javax.swing.JTable commentsTable;
    private javax.swing.JButton commetAddButton;
    private javax.swing.JTextField completeDateTextField;
    private javax.swing.JTextField createDateTextField;
    private javax.swing.JTextField damageCauseTextField;
    private javax.swing.JComboBox dayComboBox;
    private javax.swing.JButton editCommentButton;
    private javax.swing.JButton endsCalendarButton;
    private javax.swing.JTextField endsTextField;
    private javax.swing.JTextField estHrsTextField;
    private javax.swing.JComboBox freqComboBox;
    private javax.swing.JCheckBox holidaysCheckBox;
    private javax.swing.JComboBox holidaysComboBox;
    private javax.swing.JButton jButton5;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField locationTextField;
    private javax.swing.JButton materialsCalendarButton;
    private javax.swing.JTextArea materialsTextArea;
    private javax.swing.JTextArea reasonTextArea;
    private javax.swing.JCheckBox recurringCheckBox;
    private javax.swing.JButton removeCommentButton;
    private javax.swing.JTextField requestDateTextField;
    private javax.swing.JComboBox requestedByComboBox;
    private javax.swing.JTextField requestedByTextField;
    private javax.swing.JTextField ridTextField;
    private javax.swing.JRadioButton routineButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JCheckBox signedByCheckBox;
    private javax.swing.JComboBox signedByComboBox;
    private javax.swing.JTextField signedByTextField;
    private javax.swing.JButton springPresetButton;
    private javax.swing.JButton startsCalendarButton;
    private javax.swing.JTextField startsTextField;
    private javax.swing.JComboBox statusComboBox;
    private javax.swing.JCheckBox suspendCheckBox;
    private javax.swing.JRadioButton urgentButton;
    private javax.swing.JButton winterPresetButton;
    private javax.swing.JTextArea workRequiredTextArea;
    private javax.swing.JComboBox workslatesComboBox;
    // End of variables declaration//GEN-END:variables

}